jQuery(document).ready(function($){
   
    //init Thickbox
    
    ////stop the flash from happening
	$('#TB_window').css('opacity',0);
	
	function calcTB_Pos() {
		$('#TB_window').css({
	   	   'height': ($('#TB_ajaxContent').outerHeight() + 30) + 'px',
	   	   'top' : (($(window).height() + $(window).scrollTop())/2 - (($('#TB_ajaxContent').outerHeight()-$(window).scrollTop()) + 30)/2) + 'px',
	   	   'opacity' : 1
		});
	}
	
	setTimeout(calcTB_Pos,100);
	
	$(window).resize(calcTB_Pos);
	
	
  //Upload function
  initUpload();
			
	function initUpload(clone){
		var itemToInit = null;
		itemToInit = typeof clone !== 'undefined' ? clone : $('.shortcode-dynamic-item');
		
		itemToInit.find('.redux-opts-upload').on('click',function(e) {
		
		    var activeFileUploadContext = jQuery(this).parent();
		    var relid = jQuery(this).attr('rel-id');
		
		    e.preventDefault();
		
		    // if its not null, its broking custom_file_frame's onselect "activeFileUploadContext"
		    custom_file_frame = null;
		
		    // Create the media frame.
		    custom_file_frame = wp.media.frames.customHeader = wp.media({
		        // Set the title of the modal.
		        title: jQuery(this).data("choose"),
		
		        // Tell the modal to show only images. Ignore if want ALL
		        library: {
		            type: 'image'
		        },
		        // Customize the submit button.
		        button: {
		            // Set the text of the button.
		            text: jQuery(this).data("update")
		        }
		    });
		
		    custom_file_frame.on( "select", function() {
		        // Grab the selected attachment.
		        var attachment = custom_file_frame.state().get("selection").first();
		
		        // Update value of the targetfield input with the attachment url.
		        jQuery('.redux-opts-screenshot',activeFileUploadContext).prop('src', attachment.attributes.url);
		        jQuery('#' + relid ).val(attachment.attributes.url).trigger('change');
		
		        jQuery('.redux-opts-upload',activeFileUploadContext).hide();
		        jQuery('.redux-opts-screenshot',activeFileUploadContext).show();
		        jQuery('.redux-opts-upload-remove',activeFileUploadContext).show();
				});
		
				custom_file_frame.open();
		});
	
	 	itemToInit.find('.redux-opts-upload-remove').on('click', function( event ) {
	      var activeFileUploadContext = jQuery(this).parent();
	      var relid = jQuery(this).attr('rel-id');
	
	      event.preventDefault();
	
	      jQuery('#' + relid).val('');
	      jQuery(this).prev().fadeIn('slow');
	      jQuery('.redux-opts-screenshot',activeFileUploadContext).fadeOut('slow');
	      jQuery(this).fadeOut('slow');
	  });
	}
  


	//The chosen one
	$("select#thb-shortcodes").chosen();
	$(".colorpicker").wpColorPicker({
		palettes: false
	});
    var ed = tinyMCE.activeEditor;
    
    function dynamic_items(){
    	
    	var name = $('#thb-shortcodes').val(),
    			content = '';
	    
	    switch(name) {
	    	//tabs
	    	case 'tabs':
			    if( $('.shortcode-options[data-name='+name+']').is(':visible') ){
			    	$('.shortcode-options[data-name='+name+'] .shortcode-dynamic-item-input').each(function(){
			    	   if( $(this).val() != '' ) {
			    	   	i = $(this).parent().parent().find('.shortcode-dynamic-item-input-icon').val();
			    	   		if(i) { var icon = 'icon="'+i+'"' } else { var icon = '' }
			    			tabContent = $(this).parents('.shortcode-dynamic-item').find('.shortcode-dynamic-item-text').val();
			    			content += ' [tab title="'+$(this).val()+'" '+icon+'] '+tabContent+' [/tab] '; 
			    		}
			    	});
			    }   
	    		$('#shortcode-storage-thb').html('[tabs]'+content+'[/tabs]');
	    	break;
	    	
            case 'image_frame':
				if( $('.shortcode-options[data-name='+name+']').is(':visible') ){
	    	  	var align = $('.shortcode-options[data-name='+name+'] .shortcode-dynamic-item').find('.shortcode-dynamic-item-input-align').find('option:selected').val(),
    	  			image = $('.shortcode-options[data-name='+name+'] .shortcode-dynamic-item').find('.redux-opts-screenshot:first').attr('src');
	    	      }   
	    		$('#shortcode-storage-thb').html('[image_frame align="'+align+'" img="'+image+'"]');
			break;
	    }
    }
    
    function update_shortcode(){
		
			var name = $('#thb-shortcodes').val(),
					dataType = $('#options-'+name).data('type'),
					content = '';
			
			if(dataType == 'dynamic') {
				dynamic_items();
				return false;
			}
			
			switch(name) {
			     case 'portfolio':
					var id_1 = $('select#block_1').val(),
                        id_2 = $('select#block_2').val(),
                        id_3 = $('select#block_3').val(),
                        id_4 = $('select#block_4').val(),
                        id_5 = $('select#block_5').val(),
                        id_6 = $('select#block_6').val(),
                        id_7 = $('select#block_7').val();
					content = '[portfolio block_1="'+id_1+'" block_2="'+id_2+'" block_3="'+id_3+'" block_4="'+id_4+'" block_5="'+id_5+'" block_6="'+id_6+'" block_7="'+id_7+'"]';
			}
			
			$('#shortcode-storage-thb').html(content);
	 	}
   
  ///// EVENTS /////
	
		// Main Select Change
    $('#thb-shortcodes').change(function(){
			$('.shortcode-options').hide();
			$('#options-'+$(this).val()).show();
			update_shortcode();
    });
		    
		// Radio Change
    $('#add-shortcode').click(function(){
    	var name = $('#thb-shortcodes').val(),
    			dataType = $('#options-'+name).attr('data-type');
    			
    	update_shortcode();
			ed.selection.setContent($('#shortcode-storage-thb').html());
			
			tb_remove();
		
			return false;
    });
		
		// Radio Change
		$('[id^=shortcode-option]').change(function(){
			update_shortcode();
    });
    
        
        
 		// Add Item    
    var count = 0;
 	$('.add-list-item').click(function(){
    	if(!$(this).hasClass('repertoire-to-parcours')) {
    	   if(!$(this).parent().find('.remove-list-item').is(':visible')) $(this).parent().find('.remove-list-item').show();
    	
        	//clone item 
        	var $clone = $(this).parent().find('.shortcode-dynamic-item:first').clone();
        			
        	$clone.find('input[type=text], textarea').prop('value','');
        	
        	
        	//init new upload button and clear image if it's an upload
        	if( $clone.find('.redux-opts-upload').length > 0 ) {
        		$clone.find('.redux-opts-screenshot').prop('src','');
        		$clone.find('.redux-opts-upload-remove').hide();
        		$clone.find('.redux-opts-upload').css('display','inline-block');
        		setTimeout(function(){ initUpload($clone) },200);
        	}
        	
        	//append clone
			$(this).parent().find('.shortcode-dynamic-items').append($clone);
            
			return false;
    	} else {
            
            if(!$(this).parent().find('.remove-list-item').is(':visible')) $(this).parent().find('.remove-list-item').show();
            
            //clone item 
        	var $clone = $(this).parent().find('.shortcode-dynamic-item:first').clone();
            
            count++;
            
            $clone.attr('id','count-'+count);
            
            $clone.find('input[type=text], textarea').prop('value','');
            
            //init new upload button and clear image if it's an upload
        	if( $clone.find('.redux-opts-upload').length > 0 ) {
        		$clone.find('.redux-opts-screenshot').prop('src','');
        		$clone.find('.redux-opts-upload-remove').hide();
        		$clone.find('.redux-opts-upload').css('display','inline-block');
        		setTimeout(function(){ initUpload($clone) },200);
        	}
            
            //append clone
            $(this).parent().find('.shortcode-dynamic-items').append($clone);
            
            var new_main_e = $("#count-"+count+' .shortcode-dynamic-item-repertoire-service-select'),
                new_main_e_val = new_main_e.val() != null ? new_main_e.val() : "empty";
            
            get_repertoire_by_service(new_main_e_val, 'count-'+count);
            
            return false;
    	}
    });
		
		// Remove Item
    $('.remove-list-item').hide().live('click', function(){
    	if($(this).parent().find('.shortcode-dynamic-item').length > 1){
    		$(this).parent().find('#options-item .shortcode-dynamic-item:last').remove();
				dynamic_items();	
    	}
    	if($(this).parent().find('.shortcode-dynamic-item').length == 1) $(this).hide();	
			return false;
    });
    
});